package bill.study.algorithms.linkedlist;

import java.util.ArrayList;
import java.util.List;

public class ReverseInPairs {
	
	
	private static void reverseInPairs(Node head) {

		if (head == null || head.next == null) {
			return;
		}

		Node runner = head;
		while (runner != null && runner.next != null) {
			int temp = runner.val;
			runner.val = runner.next.val;
			runner.next.val = temp;
			runner = runner.next.next;
		}
	}
	
	
	public static void main(String[] args) {
		/**
		 * 1. Test reverse in pairs
		 */

		Node head = new Node(1, new Node(2, new Node(3, new Node(4, null))));
		System.out.println(head);
		reverseInPairs(head);
		System.out.println(head);

		head = null;
		System.out.println(head);
		reverseInPairs(head);
		System.out.println(head);

		head = new Node(1, new Node(2, new Node(3, null)));
		System.out.println(head);
		reverseInPairs(head);
		System.out.println(head);

		head = new Node(1, null);
		System.out.println(head);
		reverseInPairs(head);
		System.out.println(head);

		

		/**
		 * testing pass by reference
		 */
		System.out
				.println("Although they claims that Java always 	 passes by reference. We have to understand the reference is copied. (it is a fresh pointer)");
		List<Integer> l = new ArrayList<Integer>();
		l.add(2);
		System.out.println(l);
		testPassingByReference(l);
		System.out.println(l);

	}

	private static class Node {
		int val;
		Node next;

		public Node(int v, Node n) {
			this.val = v;
			this.next = n;
		}

		public String toString() {
			StringBuilder sb = new StringBuilder();
			Node runner = this;
			while (runner != null) {
				sb.append(runner.val + " ");
				runner = runner.next;
			}
			return sb.toString();
		}
	}



	

	private static void testPassingByReference(List<Integer> list) {
		list = new ArrayList<Integer>();
		list.add(1);
	}

}
